import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Spin, message, Button, Space, Table } from 'antd';
import { DownloadOutlined, EditOutlined } from '@ant-design/icons';
import { DocumentUtils, FilePreviewUtils } from '../utils/documentUtils';
import { HotTable } from '@handsontable/react';
// import 'handsontable/dist/handsontable.full.min.css';

import mammoth from "mammoth";
import '../pages/cssmodule/word-preview-content.module.css'

const DocumentPreview = ({
  visible,
  fileUrl,
  fileName,
  onClose,
  baseUrl = 'http://localhost:3000'
}) => {
  const [loading, setLoading] = useState(false);
  const [previewData, setPreviewData] = useState(null);

  const loadPreview = useCallback(async () => {
    if (!fileUrl) return;
    setLoading(true);
    try {
      const fullUrl = FilePreviewUtils.getPreviewUrl(fileUrl, baseUrl);
      const fileType = DocumentUtils.getFileType(fileName);

      if (fileType === 'image') {
        // 图片直接显示
        setPreviewData({ type: 'image', url: fullUrl });
      } else if (fileType === 'pdf') {
        // PDF直接显示
        setPreviewData({ type: 'pdf', url: fullUrl });
      } else if (fileType === 'excel') {
        // Excel需要下载并解析
        await loadExcelPreview(fullUrl);
      } else if (fileType === 'word') {
        // Word需要下载并解析
        await loadWordPreview(fullUrl);
      }
    } catch (error) {
      console.error('预览加载失败:', error);
      message.error('文件预览失败');
    } finally {
      setLoading(false);
    }
  }, [fileUrl, fileName, baseUrl]);

  const loadExcelPreview = async (url) => {
    const response = await fetch(url);
    const blob = await response.blob();
    const file = new File([blob], fileName, { type: blob.type });
    const data = await DocumentUtils.processExcelFile(file);
    setPreviewData(data);
  };
  // 解析word文件
  const loadWordPreview = async (url) => {
    try {
      const response = await fetch(url);
      console.log(response);
      
      const blob = await response.blob();
      const file = new File([blob], fileName, { type: blob.type });
      // 判断是否为标准docx
      if (!(await DocumentUtils.isRealDocx(file))) {
        message.error('该文件不是标准 docx，无法在线预览，请用 Word 打开或重新上传。');
        setLoading(false);
        return;
      }
      // 用mammoth解析docx为html
      const arrayBuffer = await blob.arrayBuffer();
      const result = await mammoth.convertToHtml({ arrayBuffer }, {
        convertImage: mammoth.images.inline(function (element) {
          return element.read("base64").then(function (imageBuffer) {
            return {
              src: "data:" + element.contentType + ";base64," + imageBuffer
            };
          });
        })
      });
      setPreviewData({ type: 'word', html: result.value });
    } catch (error) {
      console.error('Word预览失败:', error);
      message.error('Word文件预览失败');
    }
  };

  useEffect(() => {
    if (visible && fileUrl) {
      loadPreview();
    }
  }, [visible, fileUrl, loadPreview]);

  const handleDownload = async () => {
    const downloadUrl = FilePreviewUtils.getDownloadUrl(fileUrl, baseUrl);
    if (/^blob:/.test(downloadUrl)) {
      // 直接下载 blob
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } else if (/^data:image/.test(downloadUrl)) {
      // base64
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = fileName || 'image.png';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } else {
      // 普通 url，fetch 转 blob
      const response = await fetch(downloadUrl);
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  const renderPreviewContent = () => {
    if (!previewData) return null;

    switch (previewData.type) {
      case 'image':
        return (
          <div style={{ textAlign: 'center' }}>
            <img
              src={previewData.url}
              alt={fileName}
              style={{ maxWidth: '100%', maxHeight: '500px', objectFit: 'contain' }}
            />
          </div>
        );

      case 'pdf':
        return (
          <iframe
            src={previewData.url}
            width="100%"
            height="600px"
            style={{ border: 'none' }}
            title={fileName}
          />
        );

      case 'excel':
        return (
          <div>
            {previewData.sheetNames.map((sheetName) => (
              <div key={sheetName} style={{ marginBottom: '20px' }}>
                <h4>{sheetName}</h4>
                <HotTable
                  data={previewData.sheets[sheetName]}
                  colHeaders={true}
                  rowHeaders={true}
                  readOnly={true}
                  width="100%"
                  height="auto"
                  licenseKey="non-commercial-and-evaluation"
                  mergeCells={previewData.merges[sheetName]}
                  colWidths={[120, 120, 120, 120, 120, 120, 120, 120, 120, 120]} // 每列宽度
                  cell={
                    previewData.sheets[sheetName][0]
                      ? previewData.sheets[sheetName][0].map((_, colIndex) => ({
                        row: 0,
                        col: colIndex,
                        className: 'htHeader'
                      }))
                      : []
                  }
                />
              </div>
            ))}


          </div>
        );

      case 'word':
        return (
          <div
            className='word'
            style={{
              overflow: 'auto',
              // maxHeight: '500px',
              padding: '10px',
            }}
            dangerouslySetInnerHTML={{ __html: previewData.html }}
          />
        );
      default:
        return <div>不支持的文件类型</div>;
    }
  };

  return (
    <Modal
      title={`文件预览 - ${fileName}`}
      open={visible}
      onCancel={onClose}
      width="80%"
      footer={[
        <Button key="download" icon={<DownloadOutlined />} onClick={handleDownload}>
          下载
        </Button>,
        <Button key="close" onClick={onClose}>
          关闭
        </Button>
      ].filter(Boolean)}
    >
      <Spin spinning={loading}>
        {renderPreviewContent()}
      </Spin>
    </Modal>
  );
};

export default DocumentPreview;